package com.bruce.starts.demo.commonerror.spring;

import com.bruce.starts.demo.commonerror.dto.UserDto;
import com.bruce.starts.demo.commonerror.entity.UserEntity;
import com.bruce.starts.demo.commonerror.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author luotuan
 * @Description
 * @create 2021-05-12 17:06
 **/
@Slf4j
@RestController
@RequestMapping("metrics")
public class MetricsController {
    @Autowired
    private UserService userService;

    @PostMapping(value = "transaction")
    public int transaction(@RequestBody UserDto user){
        UserEntity userEntity = new UserEntity();
        userEntity.setId(user.getId());
        userEntity.setName(user.getName().orElse(""));
        userEntity.setNickName("guest" + userEntity.getName());
        userEntity.setAge(user.getAge().orElseThrow(() -> new IllegalArgumentException("用户的年龄不能为空")));
        try {
            userService.createUser(userEntity);
        }catch (Exception e){
            log.error("create user failed because {}",e.getMessage());
        }
        return userService.getUserCount(user.getName().get());
    }
}
